-- UIMonthlyCard
-- Create by huanghr
-- 月卡信息界面

-- UIMonthlyCard继承自Layer
UIMonthlyCard = class("UIMonthlyCard", function()
    return cc.Layer:create();
end);

function UIMonthlyCard.create()
    return UIMonthlyCard.new();
end

-- 构造函数
function UIMonthlyCard:ctor()
    self:setName("UIMonthlyCard");
    self.info = info;

    -- 初始化
    local node = cc.CSLoader:createNode("layout/workshop/WorkShopSign.csb");
    self:addChild(node);
    self.node = node;

    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 注册事件处理回调函数
function UIMonthlyCard:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIHeroAttrib 界面析构清理");

            EventMgr.removeAll("UIMonthlyCard");

            local uiForm = UIMgr.getCurrentScene():getFormByName("UINewWorkshop");
            if uiForm then
                -- 显示底部信息
                uiForm:showBottomMenu();
            end
        elseif ev == "enter" then
            local uiForm = UIMgr.getCurrentScene():getFormByName("UINewWorkshop");
            if uiForm then
                -- 隐藏底部信息
                uiForm:hideBottomMenu();
            end
        end
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UIMonthlyCard", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIMonthlyCard" then
            if not AlchemyWorkshopM.getWorkshop() or not UIMgr:getCurrentScene().topMenu then
                return;
            end
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_WORKER);
        end
    end);

    -- 关注月卡奖励是否可领取结果
    EventMgr.register("UIMonthlyCard", event.CHECK_SUPERIOR_BONUS, function(para)
        local haveBonus = para["have_bonus"];

        if haveBonus == 1 then
            -- 服务器已经确认有奖励了，此时客户端再做奖励操作。防止客户端时间过快而出现数据异常
            SuperiorM.takeDailyBonus();
            self:redraw();
        else
            confirm2(CONFIRM_TYPE_OK, getLocStr("system_prompt"), getLocStr("cant_take_superior_bonus_now"));
        end
    end);
end

-- 注册点击事件
function UIMonthlyCard:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIMonthlyCard");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册升级按钮
    local btnUpgrade = findChildByName(self.node, "BT/btn_upgrade");
    local function onUpgradeClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 如果已过期则关闭本界面
            if SuperiorM.isOverdue() then
                alert(getLocStr("superior_is_overdue"));
                UIMgr.getCurrentScene():removeFormByName("UIMonthlyCard");
                return;
            end

            local cardLevel = SuperiorM.getSuperiorLevel();
            local upgradeLevel = cardLevel + 1;
            local msg = self:editMsg(upgradeLevel);

            local title = SuperiorM.query(upgradeLevel, "name");

            -- 升级
            local function tryUpgrade()
                local curLevel = SuperiorM.getSuperiorLevel();
                if curLevel == 0 then
                    return;
                end

                -- 没有下一个等级了
                local nextLevel = curLevel + 1;
                if not SuperiorM.query(nextLevel) then
                    trace("SuperiorM", "没有下一个等级。");
                    return;
                end

                -- 钻石不足，跳转到购买钻石界面
                local cost = SuperiorM.query(curLevel, "upgrade_cost") or {};
                for attrib, value in pairs(cost) do
                    if type(attrib) == "string" and
                        ME.user:queryAttrib(attrib) < value then
                        showGemLackConfirm();
                        return;
                    end
                end

                -- 升级
                if SuperiorM.upgrade() then
                    self:redraw();

                    self:playUpgradeEffect();
                end
            end

            confirm2(CONFIRM_TYPE_OK, title, msg, tryUpgrade, nil, "", nil, { ["form_name"] = "UIMonthlyCard",});
        end
    end
    btnUpgrade:addTouchEventListener(onUpgradeClick);
    TextStyleM.setTextStyle(btnUpgrade, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnUpgrade:setTitleText(getLocStr("btn_text_upgrade"));

    -- 注册奖励领取按钮
    local btnUpgrade = findChildByName(self.node, "CT/btn_gain");
    local function onTakeClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if not SuperiorM.cantakeBonus() then
                return;
            end

            -- 先到服务器确认奖励是否可领取
            Operation.cmd_check_superior_bonus();
        end
    end
    btnUpgrade:addTouchEventListener(onTakeClick);
    TextStyleM.setTextStyle(btnUpgrade, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnUpgrade:setTitleText(getLocStr("take_bonus"));
end

-- 界面重绘
function UIMonthlyCard:redraw()
    self.node:stopAllActions();
    -- 取得当前月卡的等级和信息
    local cardLevel = SuperiorM.getSuperiorLevel();
    local cardInfo = SuperiorM.query(cardLevel);

    -- 设置标题样式
    local titleLabel = findChildByName(self.node, "CT/template/title");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(cardInfo.name);

    -- 增益效果描述
    local workTime = cardInfo.workshop/3600;
    local bonus = cardInfo.daily_bonus[1];
    local itemBonus = cardInfo.daily_bonus[2];
    local gemNum = bonus[3];
    local itemName = ItemM.query(itemBonus[2], "name");
    local itemNum = itemBonus[3]
    local descLabel = findChildByName(self.node, "CT/desc");
    local desc = string.format(getLocStr("monthly_card_buff"), workTime, gemNum, itemNum, itemName);
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    descLabel = applyString(descLabel, desc);

    -- 重绘招牌图标
    -- 图标
    local iconBg = findChildByName(self.node, "CT/icon_bg");
    local fileName = "bg3";
    iconBg:loadTexture(getWorkshopStrengthenIconPath(fileName));

    local icon = findChildByName(self.node, "CT/icon");
    local level = SuperiorM.getSuperiorLevel();
    local iconFileName = "icon_" .. level;
    icon:loadTexture(getSignIcon(iconFileName));

    self:checkTakeButton();
    self:checkShowUpgradeTip();
    self:checkUpgradeButton();

    -- 获得下次领取时间
    local timeLabel = findChildByName(self.node, "CT/time_label");
    local superiorData = SuperiorM.getSuperiorData();
    local startTime = TimeM.getServerTime();
    local leftDay = math.ceil((superiorData.overdue - startTime) / (3600*24));

    local function tick()
        local leftTime = SuperiorM.nextBonusTime();
        local msg = nil;
        local descLabel = findChildByName(self.node, "CT/desc");
        if leftTime <= 0 then
            local desc = string.format(getLocStr("monthly_card_buff"), workTime, gemNum, itemNum, itemName);
            TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
            descLabel = applyString(descLabel, desc);

            startTime = TimeM.getServerTime();

            leftDay = math.ceil((superiorData.overdue - startTime) / (3600*24));
            msg = string.format(getLocStr("off_next_time"), 0, 0, 0, leftDay);
            TextStyleM.setTextStyle(timeLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
            timeLabel = applyString(timeLabel, msg);

            -- 重绘领取按钮
            self:checkTakeButton();
        else
            local secs = math.floor(leftTime % 60);
            local hours = math.floor(leftTime / 3600);

            local mins  = math.floor((leftTime % 3600) / 60);
            msg = string.format(getLocStr("off_next_time"), hours, mins, secs, leftDay);
            TextStyleM.setTextStyle(timeLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
            timeLabel = applyString(timeLabel, msg);

            TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
            descLabel = applyString(descLabel, desc);
        end
        performWithDelay(self.node, tick, 1);
    end

    tick();
end

-- 检查领取按钮
function UIMonthlyCard:checkTakeButton()
    local btnTake = findChildByName(self.node, "CT/btn_gain");
    if SuperiorM.cantakeBonus() then
        btnTake:setBright(true);
        btnTake:setTouchEnabled(true);
    else
        btnTake:setBright(false);
        btnTake:setTouchEnabled(false);
    end
end

-- 检查升级按钮是否显示提示
function UIMonthlyCard:checkShowUpgradeTip()
    local isCanLevelUp = SuperiorM.canUpgrade();

    local hintNode = findChildByName(self.node, "BT/btn_upgrade/icon");
    checkBlueBubbleStatus(hintNode, isCanLevelUp, 0.75);
end

-- 当前级数最大升级按钮隐藏
function UIMonthlyCard:checkUpgradeButton()
    local upgradeButton = findChildByName(self.node, "BT/btn_upgrade");
    upgradeButton:setVisible(true);

    local curLevel = SuperiorM.getSuperiorLevel();
    if curLevel == 0 then
        upgradeButton:setVisible(false);
    end

    -- 没有下一个等级了
    local nextLevel = curLevel + 1;
    if not SuperiorM.query(nextLevel) then
        trace("SuperiorM", "没有下一个等级。");
        upgradeButton:setVisible(false);
    end
end

-- 编辑升级信息
function UIMonthlyCard:editMsg(cardLevel)
    -- 升级后的信息
    local cost = SuperiorM.query(cardLevel - 1, "upgrade_cost");
    local cardInfo = SuperiorM.query(cardLevel);

    local addDays = cardInfo.duration / (3600*24);

    -- 炼金增益和奖励
    local workTime = cardInfo.workshop/3600;
    local bonus = cardInfo.daily_bonus[1];
    local itemBonus = cardInfo.daily_bonus[2];
    local gemNum = bonus[3];
    local itemName = ItemM.query(itemBonus[2], "name");
    local itemNum = itemBonus[3]

    -- 剩余天数
    local superiorData = SuperiorM.getSuperiorData();
    local startTime = TimeM.getServerTime();
    local leftDay = math.ceil((superiorData.overdue - startTime) / (3600*24));

    -- 升级后的天数
    local upgradeDays = addDays + leftDay;

    -- 升级后的总收益
    local totalAmount = addDays * gemNum;

    -- 升级后的效果
    local str = string.format(getLocStr("monthly_card_buff"), workTime, gemNum, itemNum, itemName);

    -- 超值计算
    local value = math.floor(totalAmount / cost.gem * 100);

    local msg = string.format(getLocStr("superior_upgrade"), cost.gem, addDays, upgradeDays, gemNum, totalAmount, value);

    return msg;
end

-- 播放光效
function UIMonthlyCard:playUpgradeEffect()
    local icon = findChildByName(self.node, "CT/icon");
    playEffect(icon, 1180, 52, 58);
end

-- 适配
function UIMonthlyCard:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end